package mks.webshop.controller;

import static java.lang.System.out;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mks.webshop.Workspace;
import mks.webshop.common.AC;
import mks.webshop.entity.BasePanel;
import mks.webshop.entity.Category;
import mks.webshop.entity.Food;
import mks.webshop.entity.Logo;
import mks.webshop.entity.Notice;
import mks.webshop.entity.Order;
import mks.webshop.entity.PanelType;
import mks.webshop.entity.Product;
import mks.webshop.util.UserUtil;

import openones.gaecore.PMF;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.datastore.Text;


@Controller
@SessionAttributes
public class AdminController {
    static final Logger LOG = Logger.getLogger("AdminController");

    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    
    /** Default workspace with Vietnamese language. . */
    Workspace ws = new Workspace(AC.VN);
//    String lang = (String) session.getAttribute(AC.LANG);
//    Workspace ws = new Workspace(lang);

    /**
     * Process event hyper-link is clicked.
     * @return ModelAndView to display the login page of Google
     * @throws IOException 
     */
    @RequestMapping("/login.do")
    public ModelAndView login(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException {
        User user = UserServiceFactory.getUserService().getCurrentUser();

        if (UserUtil.isAdmin(user)) {
            session.setAttribute("isAdmin", Boolean.TRUE);
        }

        return new ModelAndView("home");
    }
    
    
    
    @RequestMapping("/editcategory")
    public ModelAndView showEditCat(@RequestParam("id") String id, @RequestParam("key") Long key, HttpSession session){
        Workspace ws = new Workspace(AC.VN);
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
//        List<Category> catListMain = ws.getCategoryList();
//        if (catListMain.isEmpty()) {
//            Category noneCat = new Category();
//            noneCat.setId("0");
//            noneCat.setName("Empty Category");
//            noneCat.setLevel(1);
//            catListMain = new ArrayList<Category>();
//            catListMain.add(noneCat);
//        }
//        List<Category> catListFull = ws.getAllCategoryList();
//        session.setAttribute("fullcategorylist", catListFull);
//        session.setAttribute("maincategorylist", catListMain);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
        session.setAttribute("address", 0);
    	Category cat = ws.getCategoryById(id);
    	ModelAndView mav = new ModelAndView("editcategory");
    	mav.addObject("category", cat);
    	return mav;
    }
    
    @RequestMapping("/editproduct")
    public ModelAndView showEditPro(@RequestParam("id") String id, @RequestParam("key") Long key, HttpSession session){
        Workspace ws = new Workspace(AC.VN);
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
//        List<Category> catListMain = ws.getCategoryList();
//        if (catListMain.isEmpty()) {
//            Category noneCat = new Category();
//            noneCat.setId("0");
//            noneCat.setName("Empty Category");
//            noneCat.setLevel(1);
//            catListMain = new ArrayList<Category>();
//            catListMain.add(noneCat);
//        }
//        List<Category> catListFull = ws.getAllCategoryList();
//        session.setAttribute("fullcategorylist", catListFull);
//        session.setAttribute("maincategorylist", catListMain);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
    	Product pro = ws.getProductById(id);
    	session.setAttribute("address", 0);
    	ModelAndView mav = new ModelAndView("editproduct");
    	mav.addObject("product", pro);
    	return mav;
    }
    
    
    @RequestMapping("/editproductimage")
    public ModelAndView showEditProImg1(@RequestParam("id") String id, @RequestParam("key") Long key, HttpSession session){
        Workspace ws = new Workspace(AC.VN);
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
//        List<Category> catListMain = ws.getCategoryList();
//        if (catListMain.isEmpty()) {
//            Category noneCat = new Category();
//            noneCat.setId("0");
//            noneCat.setName("Empty Category");
//            noneCat.setLevel(1);
//            catListMain = new ArrayList<Category>();
//            catListMain.add(noneCat);
//        }
//        List<Category> catListFull = ws.getAllCategoryList();
//        session.setAttribute("fullcategorylist", catListFull);
//        session.setAttribute("maincategorylist", catListMain);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
        session.setAttribute("address", 0);
    	Product pro = ws.getProductById(id);
    	ModelAndView mav = new ModelAndView("editproductimage");
    	mav.addObject("product", pro);
    	return mav;
    }
    
    @RequestMapping(value = "/addCategory.do")
    public String addCategory(HttpServletRequest req, HttpSession session)throws IOException{

    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    	// Get content of uploaded category picture "
        Workspace wp = new Workspace(AC.VN);    
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
    	BlobKey blobKey = blobs.get("categoryPicture");
        String name = req.getParameter("name");
        String id = req.getParameter("id");
        String parentId = req.getParameter("parentId");
        int level = Integer.parseInt(req.getParameter("level"));
        String imageKey = blobKey.getKeyString();
        
        // Get input name
        Category cat = new Category();
        cat.setId(id);
        cat.setName(name);
        cat.setParentId(parentId);
        cat.setLevel(level);
        cat.setImageKey(imageKey);
        if (!wp.isExistedCat(id)){
        	wp.save(cat);
        	req.setAttribute("error", 0);
        	return "redirect:category.html?subCatId=" + cat.getParentId() + "&level=" + (cat.getLevel() - 1);
        } else {
        	LOG.fine("Error existed Category");
//        	req.setAttribute("error", error);
        	req.setAttribute("error", 1);
        	return "redirect:category.html?subCatId=" + cat.getParentId() + "&level=" + (cat.getLevel() - 1);
        }
        
    }

    
    @RequestMapping(value = "/addproduct.do")
    public String processUploadProduct(HttpServletRequest req, HttpSession session) throws IOException{
    	
    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    	Workspace ws = new Workspace(AC.VN);
//    	String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
        // Get content of uploaded product picture "
        BlobKey blobKey = blobs.get("productPicture");

        // Get input name
        String name = req.getParameter("name");
        String id = req.getParameter("id");
        String info = req.getParameter("info");

        String catId = req.getParameter("catId");
        String unit = req.getParameter("unit");
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        long newPrice = Long.parseLong(req.getParameter("newPrice"));
        long price = Long.parseLong(req.getParameter("price"));
       // String parentId = req.getParameter("parentId");
        String imageKey = blobKey.getKeyString();
        
        
        //Save Product
        Product pro = new Product();
        pro.setName(name);
        pro.setId(id);
        pro.setInfo(info);
        pro.setCatId(catId);
        pro.setImageKey(imageKey);
        pro.setPrice(price);
        pro.setNewPrice(newPrice);
        pro.setUnit(unit);
        pro.setQuantity(quantity);
       // pro.setParentId(parentId);
        if (!ws.isExistedPro(id)){
        	req.setAttribute("error", 0);
        	ws.save(pro);	
        	return "redirect:product.html?subCatId=" + catId;   
        }else {
        	req.setAttribute("error", 2);
        	return "redirect:product.html?subCatId=" + catId;   
        }
        
        // Prepare the next view with display.jsp
         
    }
    
    @RequestMapping("/category")
    public ModelAndView showPageAddCategory(@RequestParam("subCatId") String id, @RequestParam("level") int level, HttpSession session, HttpServletRequest req) throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	List<Category> catListMain = ws.getCategoryList();
//        if (catListMain.isEmpty()) {
//            Category noneCat = new Category();
//            noneCat.setId("0");
//            noneCat.setName("Empty Category");
//            noneCat.setLevel(1);
//            catListMain = new ArrayList<Category>();
//            catListMain.add(noneCat);
//        }
//        List<Category> catListFull = ws.getAllCategoryList();
//        session.setAttribute("fullcategorylist", catListFull);
//        session.setAttribute("maincategorylist", catListMain);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
    	int subProduct;
    	Category cat1 = new Category();
    	cat1 = ws.getCategoryById(id);
    	Category cat = new Category();
    	cat.setParentId(id);
    	cat.setLevel(level + 1);
    	if (cat1 != null) {
    		subProduct = ws.getAmountSubproduct(cat1);
    	} else {
    		subProduct = 0;
    	}
    	
    	LOG.fine("Amount Sub Product" + subProduct);
    	if (subProduct == 0) {
    		req.setAttribute("error", 0);
    		ModelAndView mav = new ModelAndView("category");
        	mav.addObject("category", cat);
//            session.setAttribute("error", null);
        	return mav;
    	} else {
    		req.setAttribute("error", 4);
    		ModelAndView mav = new ModelAndView("home");
    		return mav;
    	}  	
    }
    
    /**
     * Hiển thị màn hình nhập product
     * Lấy Id của Category cha
     * Truyên Id đó vào trang product jsp
     * Hiện Id đó trong ô Product Id
     * @return
     */
    @RequestMapping("/product")
    public ModelAndView showAddProduct(@RequestParam("subCatId") String subCatId, HttpSession session, HttpServletRequest req) throws IOException{
    	Workspace ws = new Workspace(AC.VN);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
 
    	Product pro = new Product();
    	pro.setCatId(subCatId);
    	ModelAndView mav = new ModelAndView("product");
    	mav.addObject("product", pro);
    	return mav;
    
    }

    /**
     * Delete category.
     * @param catKey
     * @param session
     * @return
     */
//    @RequestMapping("/delCat.do")
//    // public String deleteCategory(@RequestParam("key") Long catKey, HttpSession session) {
//    public String deleteCategory(HttpServletRequest request, HttpSession session) {
//    	String strKey = request.getParameter("key");
//    	Long catKey = Long.valueOf(strKey);
//    	String catId = request.getParameter("id");
//        Workspace ws = new Workspace(AC.VN);
//        Category cat = ws.getCategoryById(catId);
//        LOG.fine("CatId " + cat.getId());
//        LOG.fine("Amount subCategory" + ws.getAmountSubcategory(cat));
//        LOG.fine("Amount subProduct" + ws.getAmountSubproduct(cat));
//        if (ws.getAmountSubproduct(cat) > 0) {
//        	List<Product> modProList = ws.getSubProductList(cat.getId());
//        	for (Product pro:modProList) {
//        		ws.deleteProByKey(pro.getKey());
//        	}
//        }
//        
//        if (ws.getAmountSubcategory(cat) > 0){
//        	List<Category> modCatList = ws.getAllSubCategoryList(cat.getId());
//        	for (Category cat1:modCatList) {
//        		 if (ws.getAmountSubproduct(cat1) > 0) {
//        	        	List<Product> modProList = ws.getSubProductList(cat1.get);
//        	        	for (Product pro:modProList) {
//        	        		ws.deleteProByKey(pro.getKey());
//        	        	}
//        	        }
//        		 ws.deleteCatByKey(cat1.getKey());
//        	}
//        } 
//        LOG.finest("Delete category key" + catKey);
//        ws.deleteCatByKey(catKey);
//        return "redirect:home.html";
//    }
//    
    /**
     * Delete product.
     * @param proKey
     * @param session
     * @return
     */
    @RequestMapping("/delPro.do")
    public String deleteProduct(@RequestParam("key") Long proKey, @RequestParam("id") String proId, HttpSession session)throws IOException {
        Workspace ws = new Workspace(AC.VN);
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
        
        LOG.finest("Delete product key" + proKey);
        Product pro = ws.getProductById(proId);
        String catId = pro.getCatId();
        ws.deleteProByKey(proKey);
        
        // Refresh product category
        return "redirect:listproduct.html?id=" + catId;
    }
    
    @RequestMapping("/delOrder.do")
    public String deleteOrder(@RequestParam("key") Long orderKey){
    	Workspace ws = new Workspace(AC.VN);
    	ws.deleteOrderByKey(orderKey);
    	return "redirect:listorder.html";
    }
    
    @RequestMapping("/delReceipt.do")
    public String deleteReceipt(@RequestParam("key") Long receiptKey){
    	Workspace ws = new Workspace(AC.VN);
    	ws.deleteOrderByKey(receiptKey);
    	return "redirect:listreceipt.html";
    }
    /**
     * Edit category.
     * @param catKey
     * @param session
     * @return
  	**/
    @RequestMapping(value = "/editCategory.do")
    public String editCategory(HttpServletRequest req, HttpSession session )throws IOException {
    	
    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    	// Get content of uploaded category picture "
    	Workspace ws = new Workspace(AC.VN);
//    	String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);       
    	BlobKey blobKey = blobs.get("categoryPicture");
        String name = req.getParameter("name");
        String id = req.getParameter("id");
        String parentId = req.getParameter("parentId");
        int level = Integer.parseInt(req.getParameter("level"));
        String imageKey = blobKey.getKeyString();
        
        // Get input name
        Category cat = new Category();
        cat.setId(id);
        cat.setName(name);
        cat.setParentId(parentId);
        cat.setLevel(level);
        cat.setImageKey(imageKey);
        ws.save(cat);
        return "redirect:listsubcategory.html?id=" + parentId + "&level=" + (level - 1) ;
    }
    
    
    @RequestMapping("/logo")
    public ModelAndView showPageEditLogo(HttpSession session){
    	ModelAndView mav = new ModelAndView("logo");
    	return mav;
    }
    
    /**
     * Edit logo.
     * @param session
     * @return
  	**/
    @RequestMapping(value = "/editlogo.do")
    public String editLogo(HttpServletRequest req, HttpSession session )throws IOException {
    	Workspace ws = new Workspace(AC.VN);
//    	String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    	// Get content of uploaded category picture "      
    	BlobKey blobKey = blobs.get("logoImage");
        String imageKey = blobKey.getKeyString();
        
        // Get input name
        Logo logo = new Logo();
        logo.setImageKey(imageKey);
        ws.save(logo);
        return "redirect:home.html";
    }
    
    
    @RequestMapping(value = "/editproduct.do")
    public String processEditProduct(HttpServletRequest req, HttpSession session) throws IOException{
//    	
//    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
//    	Map<String, BlobKey> blobs1 = blobstoreService.getUploadedBlobs(req);
//    	String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
    	Workspace ws = new Workspace(AC.VN);
        // Get content of uploaded product picture "
//        BlobKey blobKey = blobs.get("productPicture");
//        BlobKey blobKey1 = blobs.get("productLargePicture");

        // Get input name
        String name = req.getParameter("name");
        String id = req.getParameter("id");
        String description = req.getParameter("description");
        String info = req.getParameter("info");
        String catId = req.getParameter("catId");
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        String unit = req.getParameter("unit");
        long price = Long.parseLong(req.getParameter("price"));
        long newPrice = Long.parseLong(req.getParameter("newPrice"));
//        String imageKey = blobKey.getKeyString();
//        String largeImageKey = blobKey1.getKeyString();
        
        
        
        //Save Product
        Product pro = new Product();
        pro.setName(name);
        pro.setId(id);
        pro.setInfo(info);
        pro.setDescription(new Text(description));
        pro.setCatId(catId);
        pro.setQuantity(quantity);
//        pro.setImageKey(imageKey);
//        pro.setLargeImageKey(largeImageKey);
        pro.setPrice(price);
        pro.setNewPrice(newPrice);
        pro.setUnit(unit);
       // pro.setParentId(parentId);
        ws.save(pro);
        // Prepare the next view with display.jsp
        return "redirect:detailproduct.html?id=" + id;    
    }
    
    @RequestMapping(value = "/editproductimage.do")
    public String processEditProductImage(HttpServletRequest req, HttpSession session) throws IOException{
//    	
    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
//    	Map<String, BlobKey> blobs1 = blobstoreService.getUploadedBlobs(req);
//    	String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
    	Workspace ws = new Workspace(AC.VN);
        // Get content of uploaded product picture "
        BlobKey blobKey = blobs.get("productPicture");
//        BlobKey blobKey1 = blobs.get("productLargePicture");

        // Get input name
//        String name = req.getParameter("name");
        String id = req.getParameter("id");
//        String info = req.getParameter("info");
//        String catId = req.getParameter("catId");
//        long price = Long.parseLong(req.getParameter("price"));
        String imageKey = blobKey.getKeyString();
//        String largeImageKey = blobKey1.getKeyString();
        
        
        
        //Save Product
        Product pro = new Product();
//        pro.setName(name);
        	pro.setId(id);
//        pro.setInfo(info);
//        pro.setCatId(catId);
        pro.setImageKey(imageKey);
//        pro.setLargeImageKey(largeImageKey);
//        pro.setPrice(price);
       // pro.setParentId(parentId);
        ws.saveProductImage(pro);
        // Prepare the next view with display.jsp
        return "redirect:detailproduct.html?id=" + id;    
    }

    /**
     * Display editing panel.
     * @param panelId
     * @param session
     * @return
     */
    @RequestMapping("/edit-panel.do")
    public ModelAndView editPanel(@RequestParam("panelId") String panelId, @RequestParam("type") PanelType panelType, HttpSession session) {
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
    	Workspace ws = new Workspace(AC.VN);
        
        LOG.finest("Editing pannel; id=" + panelId + ";type=" + panelType);
        
        ModelAndView mav = new ModelAndView("editpanel");
        BasePanel panel = ws.getPanel(panelType);

        if (panel == null) {
            panel = new BasePanel();
            panel.setId(panelId);
            panel.setType(panelType);
        }
        mav.addObject("panel", panel);
        
        return mav;
    }

    /**
     * Saving panel.
     * @param panel
     * @param result
     * @param session
     * @return
     */
    @RequestMapping(value = "/save-panel.do", method = RequestMethod.POST)
    public String editPanel(@ModelAttribute("BasePanel") BasePanel panel, BindingResult result, HttpSession session) {
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
    	
    	Workspace ws = new Workspace(AC.VN);
        
        LOG.finest("Saving pannel; id=" + panel.getId() + ";type=" + panel.getType() + ";content=" + panel.getContent().getValue() 
                   + ";type=" + panel.getType());
        LOG.finest("Content size:" + panel.getContent().getValue() + ";size=" + panel.getContent().getValue().length());
        
        ws.savePanel(panel);
        return "redirect:home.html";
    }
    
    @RequestMapping(value = "/addnotice")
    public ModelAndView showAddNoticePage(HttpSession session) {
    	Workspace ws = new Workspace(AC.VN);
    	 BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
         session.setAttribute("rightPanel", rightPanel);
         
         // Get content of header panel
         BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
         session.setAttribute("headerPanel", headerPanel);
         
         // Get content of footer panel
         BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
         session.setAttribute("footerPanel", footerPanel);
         
         Notice note = new Notice();
         ModelAndView mav = new ModelAndView("addnotice");
         mav.addObject("notice", note);
         return mav;
    }
    
    @RequestMapping(value ="/addnotice.do")
    public String processAddNotice(HttpServletRequest req, HttpSession session){
    	Workspace ws = new Workspace(AC.VN);
    	String name = req.getParameter("name");
        String id = req.getParameter("id");
        String description = req.getParameter("description");
        
        Notice note = new Notice();
        note.setName(name);
        note.setId(id);
        note.setDescription(new Text(description));
        
        ws.save(note);
        // Prepare the next view with display.jsp
        return "redirect:listnotice.html"; 
    }
    
    @RequestMapping(value = "/editnotice")
    public ModelAndView showEditNoticePage(@RequestParam("id") String id, HttpSession session) {
    	Workspace ws = new Workspace(AC.VN);
    	 BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
         session.setAttribute("rightPanel", rightPanel);
         
         // Get content of header panel
         BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
         session.setAttribute("headerPanel", headerPanel);
         
         // Get content of footer panel
         BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
         session.setAttribute("footerPanel", footerPanel);
         
         Notice note = ws.getNoticeById(id);
         ModelAndView mav = new ModelAndView("editnotice");
         mav.addObject("notice", note);
         return mav;
    }
    
    @RequestMapping(value ="/editnotice.do")
    public String processEditNotice(HttpServletRequest req, HttpSession session){
    	Workspace ws = new Workspace(AC.VN);
    	String name = req.getParameter("name");
        String id = req.getParameter("id");
        String description = req.getParameter("description");
        
        Notice note = new Notice();
        note.setName(name);
        note.setId(id);
        note.setDescription(new Text(description));
        
        ws.save(note);
        // Prepare the next view with display.jsp
        return "redirect:listnotice.html"; 
    }
    
    @RequestMapping("/delNotice.do")
    public String deleteNotice(@RequestParam("key") Long key, HttpSession session)throws IOException {
        Workspace ws = new Workspace(AC.VN);
        ws.deleteNoticeByKey(key);
        
        // Refresh product category
        return "redirect:listnotice.html";
    }
    
    ///Controller cho food
    @RequestMapping(value = "/addfood")
    public ModelAndView showAddFoodPage(HttpSession session) {
    	
    	Workspace ws = new Workspace(AC.VN);
    	BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
         
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
         
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
         
        Food food = new Food();
        ModelAndView mav = new ModelAndView("addfood");
        mav.addObject("food", food);
        return mav;
    }
    
    @SuppressWarnings("deprecation")
	@RequestMapping(value ="/addfood.do")
    public String processAddFood(HttpServletRequest req, HttpSession session){
    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    	BlobKey blobKey = blobs.get("foodImage");
    	Workspace ws = new Workspace(AC.VN);
    	String name = req.getParameter("name");
        String code = req.getParameter("code");
        String detail = req.getParameter("detail");
        String imageKey = blobKey.getKeyString();
        
        Food food = new Food();
        food.setName(name);
        food.setCode(code);
        food.setDetail(new Text(detail));
        food.setImageKey(imageKey);
        
        ws.saveFood(food);
        // Prepare the next view with display.jsp
        return "redirect:listfood.html"; 
    }
    
    @RequestMapping("/delfood.do")
    public String deleteFood(@RequestParam("id") long id, HttpSession session)throws IOException {
        Workspace ws = new Workspace(AC.VN);
        ws.deleteFood(id);
        
        // Refresh product category
        return "redirect:listfood.html";
    }
    
    @RequestMapping(value = "/editfood")
    public ModelAndView showEditFoodPage(@RequestParam("id") String code, HttpSession session) {
    	Workspace ws = new Workspace(AC.VN);
    	 BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
         session.setAttribute("rightPanel", rightPanel);
         
         // Get content of header panel
         BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
         session.setAttribute("headerPanel", headerPanel);
         
         // Get content of footer panel
         BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
         session.setAttribute("footerPanel", footerPanel);
         
         Food food = ws.getFoodByCode(code);
         ModelAndView mav = new ModelAndView("editfood");
         mav.addObject("food", food);
         return mav;
    }
    
    @RequestMapping(value ="/editfood.do")
    public String processEditFood(HttpServletRequest req, HttpSession session){
    	Workspace ws = new Workspace(AC.VN);
    	String name = req.getParameter("name");
        String code = req.getParameter("code");
        String detail = req.getParameter("detail");
        
        Food food = new Food();
        food.setName(name);
        food.setCode(code);
        food.setDetail(new Text(detail));
        
        ws.saveFood(food);
        // Prepare the next view with display.jsp
        return "redirect:listfood.html"; 
    }
    
    @RequestMapping("/editfoodimage")
    public ModelAndView showEditFoodImage(@RequestParam("code") String code, @RequestParam("key") Long key, HttpSession session){
        Workspace ws = new Workspace(AC.VN);

        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
        session.setAttribute("address", 0);
    	Food food = ws.getFoodByCode(code);
    	ModelAndView mav = new ModelAndView("editfoodimage");
    	mav.addObject("food", food);
    	return mav;
    }
    
    @RequestMapping(value = "/editfoodimage.do")
    public String processEditFoodImage(HttpServletRequest req, HttpSession session) throws IOException{
    	
    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    	Workspace ws = new Workspace(AC.VN);
        // Get content of uploaded product picture "
        BlobKey blobKey = blobs.get("foodImage");
        String code = req.getParameter("code");
        String imageKey = blobKey.getKeyString();
        
        //Save Product
        Food food = new Food();
        food.setCode(code);

        food.setImageKey(imageKey);
//        pro.setLargeImageKey(largeImageKey);
//        pro.setPrice(price);
       // pro.setParentId(parentId);
        ws.saveFoodImage(food);
        // Prepare the next view with display.jsp
        return "redirect:detailfood.html?id=" + code;    
    }
    
    @RequestMapping("/delUser.do")
    public String deleteUser(@RequestParam("key") Long key, @RequestParam("id") String id, HttpSession session)throws IOException {
        Workspace ws = new Workspace(AC.VN);
        ws.deleteUserByKey(key);
        return "redirect:listuser.html";
    }
    
    @RequestMapping("/edituser")
    public ModelAndView showEditUserPage(@RequestParam("id") String id, HttpSession session)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	mks.webshop.entity.User modUser = ws.getUserById(id);
    	ModelAndView mav = new ModelAndView("edituser");
    	mav.addObject("user", modUser);
    	return mav;
    	
    }
    @RequestMapping("/edituser.do")
    public String processEditUser(HttpSession session, HttpServletRequest req)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	String id = req.getParameter("id");
    	String password = req.getParameter("password");
    	String name = req.getParameter("name");
    	String email = req.getParameter("email");
    	String phonenumber = req.getParameter("phonenumber");
    	mks.webshop.entity.User modUser = new mks.webshop.entity.User();
    	modUser.setId(id);
    	modUser.setName(name);
    	modUser.setPassword(password);
    	modUser.setEmail(email);
    	modUser.setPhonenumber(phonenumber);
    	ws.save(modUser);
    	return "redirect:detailuser.html?id=" + id; 	
    }
    
    @RequestMapping("/listorder.html")
    public String listOrder(ModelMap model)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	List<Order> orders = ws.getOrdersByState(false);
    	System.out.println(orders.size());
    	model.addAttribute("orders", orders);
    	return "listorder";
    }
   
    @RequestMapping("/listreceipt.html")
    public String listReceipt(ModelMap model)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	List<Order> receipts = ws.getOrdersByState(true);
    	
    	for (Order order : receipts) {
			System.out.println(order.getCode() + "&status: " + order.getIsDone());
		}
    	
    	model.addAttribute("receipts", receipts);
    	return "listreceipt";
    }
    
    @RequestMapping("/exeorder.html")
    public String setIsDone(HttpServletRequest request){	
    	String code = request.getParameter("id");
    	Workspace ws = new Workspace(AC.VN);
    	Order order = ws.getOrderByCode(code);
    	ws.setIsDone(order, true);
    	return "redirect:listorder.html";
    }
    
    @RequestMapping("/makeproductspecial")
    public String setProductSpecial(@RequestParam("id") String proId){
    	Workspace ws = new Workspace(AC.VN);
    	Product modPro = ws.getProductById(proId);
    	if (modPro.getIsSpecial() == 1){
    		ws.setProductIsSpecial(modPro, 0);
    	}
    	ws.setProductIsSpecial(modPro, 1);
    	return "detailproduct";
    	
    }
}
